package com.sys.server.modules.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sys.server.common.constants.enums.ResultSetEnum;
import com.sys.server.common.model.R;
import com.sys.server.common.utils.MD5Util;
import com.sys.server.modules.entity.UserEntity;
import com.sys.server.modules.mapper.UserMapper;
import com.sys.server.modules.service.LoginService;
import com.sys.server.modules.service.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    private static final Logger LOG = LoggerFactory.getLogger(LoginServiceImpl.class);

    @Resource
    private UserMapper userMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public R login(String username, String password) {
        R r = checkInfo(username, password);
        if (Integer.parseInt(r.get("code").toString()) == 200) {
            // todo 生成token，写入Redis
            String token = tokenService.createToken();
            redisTemplate.opsForValue().set(token, username);
            redisTemplate.expire(token, 60*60*3, TimeUnit.SECONDS);
            R res = R.ok(ResultSetEnum.SUCCESS);
            res.put("token", token);
            return res;
        }
        return r;
    }

    @Override
    public R logout(String token) {
        try {
            redisTemplate.delete(token);
            return R.ok(ResultSetEnum.SUCCESS);
        } catch (Exception e) {
            LOG.error("退出系统错误======");
            return R.ok(ResultSetEnum.FAIL);
        }
    }

    /**
     * 登录信息校验
     * 根据用户名查询数据库，校验信息是否正确
     *
     * @return
     */
    private R checkInfo(String username, String password) {
        UserEntity user = userMapper.selectOne(Wrappers.<UserEntity>query().eq("uid", username));
        if (user == null) {
            return R.ok(401, "User Not Found");
        } else {
            String salt = user.getSalt();
            String pwdhash = user.getPwdhash();
            if (!MD5Util.matches(password, salt, pwdhash)) {
                return R.ok(401, "Password Error");
            }
        }
        return R.ok(ResultSetEnum.SUCCESS);
    }

}
